<script lang="ts" setup>
import { uploadFileAPI } from '@/apis/common';
import { addRentAPI, deleteEnterpriseAPI, deleteRentAPI, exitRentAPI, getBuildingListAPI, getEnterpriseListAPI, getRentListAPI } from '@/apis/enterprise';
import AuthBtn from '@/layouts/components/AuthBtn.vue';
import type { AddRentData, BuildingListRes, EnterpriseItem, EnterpriseListQuery, RentItemRes } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormInstance, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { ref, watch } from 'vue'

// 获取企业列表数据
const form = ref<EnterpriseListQuery>({
  page: 1,
  pageSize: 10,
  name: ''
})
// const enterpriseList = ref<EnterpriseItem[]>([])
const total = ref(0)
// --前端自定义的类型，用于展示嵌套表格--
interface EnterpriseWithRent extends EnterpriseItem {
  // 合同列表
  rentList: RentItemRes[]
}
const list = ref<EnterpriseWithRent[]>([])
const getEnterpriseList = async () => {
  const res = await getEnterpriseListAPI(form.value)
  list.value = res.data.rows.map(item => ({
    ...item,
    rentList: []
  }))
  total.value = res.data.total
}
getEnterpriseList()

// 查询功能
const onSearch = () => {
  form.value.page = 1
  getEnterpriseList()
}

// 删除功能
const onDelete = async (id: number) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteEnterpriseAPI(id)
    ElMessage.success('删除成功')
    getEnterpriseList()
  }).catch(() => {
    ElMessage.warning('取消删除')
  })
}

// --------添加合同--------
const rentDialogVisible = ref(false)
// 创建变量来刷新表格展开项
const expandRow = ref<EnterpriseWithRent>()
const addRent = async (row: EnterpriseWithRent) => {
  // 操作类型，添加合同0，续签合同1
  rentForm.value.type = 0
  rentDialogVisible.value = true
  rentForm.value.enterpriseId = row.id
  expandRow.value = row
}
// 合同表单
const rentForm = ref<AddRentData>({
  buildingId: undefined,
  contractId: undefined,
  contractUrl: '',
  startTime: '',
  endTime: '',
  enterpriseId: undefined,
  type: 0
})
// 查询可租赁楼宇
const buildingList = ref<BuildingListRes[]>([])
const getBuildingList = async () => {
  const res = await getBuildingListAPI()
  buildingList.value = res.data
  // console.log('查询可租赁楼宇:', buildingList.value);
}
getBuildingList()

// 创建日期数组
const dateArr = ref<string[]>([])
watch(dateArr, (newValue) => {
  if (newValue) {
    rentForm.value.startTime = newValue[0]
    rentForm.value.endTime = newValue[1]
  } else {
    rentForm.value.startTime = ''
    rentForm.value.endTime = ''
  }
})
// 日期限制从今天开始
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}
// 上传文件
const fileList = ref<UploadUserFile[]>([])
const httpRequest = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  const res = await uploadFileAPI(fd)
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id
  // 主动触发规则校验
  rentFormRef.value?.validateField('contractUrl')
  return res.data.url
}
// 上传之前检查文件大小和类型
const beforeUpload = (rawFile: UploadRawFile) => {
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('上传文件大小不能超过 5MB!')
    return false
  }
  return true
}
// 移除文件时删除表单信息
const removeFile = () => {
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  // 主动触发规则校验
  rentFormRef.value?.validateField('contractUrl')
}

// 规则校验
const rules = {
  buildingId: [
    { required: true, message: '请选择租赁楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁结束日期', trigger: 'change' }
  ],
  contractUrl: [
    { required: true, message: '请上传租赁合同' }
  ]
}
// 创建表单实例
const rentFormRef = ref<FormInstance>()
// 关闭模态框时重置表单
const onClose = () => {
  rentFormRef.value?.resetFields()
  // 没有重置到的表单字段(因为没有在规则里面写)
  rentForm.value.contractId = undefined

  fileList.value = []
  dateArr.value = []
}
// 提交表单
const onSubmit = async () => {
  await rentFormRef.value!.validate()
  await addRentAPI(rentForm.value)
  ElMessage.success('合同添加成功')
  onExpandChange(expandRow.value!)
  rentDialogVisible.value = false
}

// -----------展开行-----------

// 展开行时获取合同列表
const onExpandChange = async (row: EnterpriseWithRent) => {
  console.log('当前行被展开/折叠', row);
  const res = await getRentListAPI(row.id)
  row.rentList = res.data
  // console.log('展开行时获取合同列表rentList',rentList.value);

}
// 退租
const exitRent = async (row: EnterpriseWithRent, contractId: number) => {
  ElMessageBox.confirm('确定要退租吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await exitRentAPI(contractId)
      ElMessage.success('退租成功')
      onExpandChange(row)
    } catch (error) {
      console.log(error)
    }
  }).catch(() => {
    ElMessage.warning('取消退租')
  })
}

// 删除合同
const deleteRent = async (row: EnterpriseWithRent, contractId: number) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRentAPI(contractId)
      ElMessage.success('删除成功')
      onExpandChange(row)
    } catch (error) {
      console.log(error)
    }
  }).catch(() => {
    ElMessage.warning('取消删除')
  })
}
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" class="search-main" v-model="form.name" @keydown.enter="onSearch"
        @clear="onSearch" />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
        <el-button v-auth="'park:enterprise:add_edit'" type="primary"
          @click="$router.push('/exterpriseAdd')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id">
        <!-- type="expand" 显示一个可展开的按钮 -->
        <el-table-column type="expand">
          <template #default="{ row: enterpriseRow }">
            <el-table :data="enterpriseRow.rentList">
              <el-table-column label="租赁楼宇" width="200" prop="buildingName" />
              <el-table-column label="租赁起始时间" width="300" prop="startTime" />
              <el-table-column label="合同状态" width="260" prop="status">
                <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row: rentRow }">
                  <el-button size="small" type="primary" :disabled="rentRow.renewFlag" link>续租</el-button>
                  <el-button size="small" type="primary" :disabled="rentRow.status === 3" link
                    @click="exitRent(enterpriseRow, rentRow.id)">退租</el-button>
                  <el-button size="small" type="primary" :disabled="rentRow.exitFlag" link
                    @click="deleteRent(enterpriseRow, rentRow.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" prop="id" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作" width="320" prop="operation">
          <template #default="{ row }">

            <AuthBtn btn-perm="park:rent:add_surrender">
              <el-button size="small" type="primary" link @click="addRent(row)">添加合同</el-button>
            </AuthBtn>

            <el-button size="small" type="primary" link
              @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button v-auth="'park:enterprise:add_edit'" size="small" type="primary" link
              @click="$router.push(`/exterpriseAdd/${row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" link @click="onDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination layout="total, sizes, prev, pager, next, jumper" :total="total" v-model:current-page="form.page"
        v-model:page-size="form.pageSize" :page-sizes="[2, 5, 10]" @change="getEnterpriseList" />
    </div>

    <!-- 添加合同模态框 -->
    <el-dialog v-model="rentDialogVisible" :title="rentForm.type ? '续签合同' : '添加合同'" width="440" @close=onClose>
      <el-form label-position="top" class="rent-form" :model="rentForm" :rules="rules" ref="rentFormRef">

        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select placeholder="请选择租赁楼宇" v-model="rentForm.buildingId" clearable>
            <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="租赁起止日期" prop="endTime">
          <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            v-model="dateArr" value-format="YYYY-MM-DD" :disabled-date="disabledDate" :before-upload="beforeUpload" />
        </el-form-item>

        <el-form-item label="租赁合同" prop="contractUrl">
          <el-upload :http-request="httpRequest" accept=".doc, .pdf" :file-list="fileList" :on-remove="removeFile">
            <el-button type="primary" plain>上传合同文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.doc.pdf，文件大小不超过5M
              </div>
            </template>
          </el-upload>

        </el-form-item>
      </el-form>
      {{ rentForm }}
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}

.rent-form {
  width: 300px;
  margin: auto;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
</style>